package com.example.spzx.Service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.spzx.Service.FileUploadService;
import com.example.spzx.model.entity.system.MinioProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;

import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {


    public String fileUpload(MultipartFile multipartFile) {
        MinioProperties minioProperties=new MinioProperties();
        try {
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint("http://127.0.0.1:9000")
                    .credentials("minioadmin", "minioadmin")
                    .build();
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket("shop-bucket").build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("shop-bucket").build());

            } else {
                System.out.println("不存在");
            }
            String dateDir= DateUtil.format(new Date(),"yyyyMMdd");
            String uuid= UUID.randomUUID().toString().replace("-","");
            String fileName=dateDir+"/"+uuid+multipartFile.getOriginalFilename();
            PutObjectArgs putObjectArgs=PutObjectArgs.builder().bucket("shop-bucket").stream(multipartFile.getInputStream(), multipartFile.getSize(), -1).object(fileName).build();
            minioClient.putObject(putObjectArgs);
            return "http://127.0.0.1:9000"+"/"+"shop-bucket"+"/"+fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
